<?php
namespace growup;

use think\facade\Cache;

class Auth
{
    // 默认配置
    public $config = [
        'auth_on' => true,
        'check_type' => 1, // 1.缓存验证，2.实时验证
//        'cache_type' => 'file' // file 文件缓存 session session缓存  感觉没有必要
        'user_table' => 'admin_user',
        'group_table' =>   'auth_group',
        'user_group_table' => 'auth_user_group',
        'rule_table' => 'auth_rule',
        'group_rule_table' => 'auth_group_rule',
    ];

    // 缓存类型
    public $cacheConfig = [
        // 缓存类型为File
        'type'  =>  'File',
        // 缓存有效期为永久有效
        'expire'=>  0,
        //缓存前缀
        'prefix'=>  'auth',
        // 指定缓存目录
        'path'  =>  '../../runtime/cache/file',

//        'file' => [
//            // 缓存类型为File
//            'type'  =>  'File',
//            // 缓存有效期为永久有效
//            'expire'=>  0,
//            //缓存前缀
//            'prefix'=>  'auth',
//            // 指定缓存目录
//            'path'  =>  '../../runtime/cache/file',
//        ],
//        'session' => [
//            // 缓存类型为Session
//            'type'  =>  '',
//            // 缓存有效期为永久有效
//            'expire'=>  0,
//            //缓存前缀
//            'prefix'=>  'auth',
//        ],
    ];


    // 权限列表
    public static $authList = [];

    public function __construct()
    {
        $this->config = array_merge($this->config, config('?auth')?config('auth'):[]);
    }

    // 检查是否具有条件
    public function check($name, $uid, $relation = 'or')
    {
        // 是否开启验证
        if (!$this->config['auth_on']) {
            return true; // 未开启返回true
        }
        $authList = $this->getAuthList($uid);
        $list = [];
        if (is_string($name)) {
            $name = explode(',', $name);
        }
        foreach ($name as $rule) {
            if (in_array($rule, $authList)) {
                $list[] = $rule;
            }
        }

        if (strtolower($relation) == 'or' and !empty($list)) {
            return true;
        }

        if (strtolower($relation) == 'and' and $list == $name) {
            return true;
        }

        return false;
    }

    // 获取用户权限列表
    public function getAuthList($uid)
    {
        if ($authList = Cache::connect($this->cacheConfig)->get($uid, [])) {
            return $authList;
        }
        // 获取所有规则
        $ruleArr = $this->getRuleArr($uid);
        if ($this->config['check_type'] == '1') {
            Cache::connect($this->cacheConfig)->set($uid, $ruleArr);
        }
        return $ruleArr;
    }

    // 获取用户所在在使用并满足条件的规则
    public function getRuleArr($uid)
    {
        // 获取所有当前用户id所有的规则
        $tablePre = config('database.prefix');
        $userGroup = $tablePre.$this->config['user_group_table'];
        $rule = $tablePre.$this->config['rule_table'];
        $groupRule = $tablePre.$this->config['group_rule_table'];

        $sql = "select rule.* from {$userGroup} as user_group 
LEFT JOIN {$groupRule} as group_rule ON user_group.gid = group_rule.gid 
LEFT JOIN {$rule} as rule ON group_rule.rid = rule.id 
WHERE user_group.uid = 1 AND rule.`status` = 1;";

        $ruleArr = \think\Db::query($sql);
        foreach ($ruleArr as $item) {
            // 比较符转换
//            $signs = [
//                'eq'    =>  '=',
//                'neq'   =>  '!=',
//                'gt'    =>  '>',
//                'egt'   =>  '>=',
//                'lt'    =>  '<',
//                'elt'   =>  '<=',
//                'heq'   =>  '===',
//                'nheq'  =>  '!==',
//            ];
            if (!empty($item['condition'])) { // 不为空必须满足条件才算作该用户的规则
                $condition = null;
                // 规则
                // [{"variable":"userInfo.level","sign":"eq","value":30,'connect':'and'}]
                $rules = json_decode($item['condition'], true);
                foreach ($rules as $rule) {
                    // 解析变量
                    $name = explode('.', $rule['variable']);
                    $variable = ${$name[0]}[$name[1]];
                    if (substr($rule['value'], 0, 5) == '$var$') {
                        $val = explode('.', substr($rule['value'], 5));
                        $value = ${$val[0]}[$val[1]];
                    } else {
                        $value = $rule['value'];
                    }
                    switch ($rule['sign']) {
                        case 'eq':
                            $where = ($variable == $value);
                            break;
                        case 'neq':
                            $where = ($variable != $value);
                            break;
                        case 'gt':
                            $where = ($variable > $value);
                            break;
                        case 'egt':
                            $where = ($variable >= $value);
                            break;
                        case 'lt':
                            $where = ($variable < $value);
                            break;
                        case 'elt':
                            $where = ($variable <= $value);
                            break;
                        case 'heq':
                            $where = ($variable === $value);
                            break;
                        case 'nheq':
                            $where = ($variable !== $value);
                            break;
                        default:
                            continue;
                    }
                    if (!is_null($condition)) {
                        switch ($rule['connect']) {
                            case 'and':
                                $condition = ($condition AND $where);
                                break;
                            case 'or':
                                $condition = ($condition OR $where);
                                break;
                            default:
                                throw new \Exception('Auth 条件连接符有误');
                        }
                    } else {
                        $condition = $where;
                    }
                    if ($condition) {
                        $rt[] = $rule['name'];
                    }
                }
            } else {
                $rt[] = $rule['name'];
            }

        }
        // 获取所有的id
    }

    // 根据其他条件判断权限

    // 如：用户的等级，用户的积分等等
    public function getUserInfo($uid)
    {

    }


}